package com.example.demo.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Liunh
 */
@JsonComponent
public class DateFormatConfig {

    private static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat DEFAULT_DATE_FORMAT1 = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat SSSZ_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

    /**
     * 日期序列化
     */
    public static class DateJsonSerializer extends JsonSerializer<Date> {
        @Override
        public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (date != null) {
                jsonGenerator.writeString(DEFAULT_DATE_FORMAT.format(date));
            }
        }
    }

    /**
     * 日期反序列化
     */
    public static class DateJsonDeserializer extends JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            try {
                String text = jsonParser.getText();
                if (StringUtils.isBlank(text)) {
                    return null;
                }
                //时间戳格式
                if (text.length() == 10) {
                    if (text.contains("-")) {
                        return DEFAULT_DATE_FORMAT1.parse(text);
                    } else {
                        return DEFAULT_DATE_FORMAT.parse(DEFAULT_DATE_FORMAT.format(Long.parseLong(text)));
                    }
                }
                if (text.length() == 13 && !text.contains("-")) {
                    return DEFAULT_DATE_FORMAT.parse(DEFAULT_DATE_FORMAT.format(Long.parseLong(text)));
                }
                //yyyy-MM-dd'T'HH:mm:ss.SSSZ
                if (text.contains("T") && text.contains("SSSZ")) {
                    return SSSZ_DATE_FORMAT.parse(text);
                }
                //DEFAULT_DATE_FORMAT
                return DEFAULT_DATE_FORMAT.parse(text);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
